package com.company.batch.reader.factory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.batch.item.file.BufferedReaderFactory;
import org.springframework.core.io.Resource;

public class CustomBufferedReaderFactory implements BufferedReaderFactory {

	Logger logger = Logger.getLogger(CustomBufferedReaderFactory.class);
	
	private String tempFileName = "tempFile.tmp";

	public BufferedReader create(Resource resource, String encoding)
			throws UnsupportedEncodingException, IOException {

		logger.info(":: Resource :: "+ resource.getFilename());
		
		File file = resource.getFile();

		if (!file.isDirectory()) {
			return new BufferedReader(new InputStreamReader(
					resource.getInputStream(), encoding));

		}

		File[] fileList = file.listFiles();
		logger.info(":: fileList :: "+ fileList.length);
		File tempFile = new File(resource.getFile().getAbsolutePath()
				+ File.pathSeparator + tempFileName);
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(
				tempFile));

		for (File fl : fileList) {
			IOUtils.copy(new BufferedReader(new FileReader(fl)), bufferedWriter);
		}

		bufferedWriter.close();

		return new BufferedReader(new FileReader(tempFile));
	}

}
